<template>
  <el-dialog
    v-model="dialogVisible"
    :title="loadingData ? '加载中...' : '编辑订单'"
    width="900px"
    @close="handleClose"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <template v-if="loadingData">
      <div class="loading-container">
        <div class="loading-content">
          <el-icon class="is-loading" style="font-size: 24px;">
            <Loading />
          </el-icon>
          <p>加载订单数据中...</p>
        </div>
      </div>
    </template>
    
    <template v-else>
      <el-form 
        ref="orderFormRef"
        :model="formData" 
        label-width="80px"
        :rules="formRules"
        validate-on-rule-change
      >
        <!-- 客户信息 -->
          <el-form-item label="客户姓名" prop="customer_name" required>
            <el-input
              v-model="formData.customer_name"
              placeholder="请输入客户姓名"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="客户电话" prop="customer_phone" required>
            <el-input
              v-model="formData.customer_phone"
              placeholder="请输入客户电话"
              maxlength="20"
              type="tel"
              show-word-limit
              @input="handlePhoneInput"
            />
          </el-form-item>

        <el-form-item label="下单时间" prop="order_time">
            <el-date-picker
              v-model="formData.order_time"
              type="datetime"
              placeholder="选择下单时间"
              style="width: 100%;"
              :default-time="['12:00:00']"
            />
          </el-form-item>

        <!-- 商品明细 -->
        <el-form-item label="商品明细" required>
          <div class="items-container">
            <!-- 添加商品表单 -->
              <div class="add-item-form">
                <el-input
                  v-model="itemForm.name"
                  placeholder="商品名称"
                  style="width: 28%; margin-right: 10px;"
                  maxlength="100"
                  show-word-limit
                />
                <span style="margin-right: 5px;">数量:</span>
                <el-input-number
                  v-model="itemForm.quantity"
                  :min="1"
                  style="margin-right: 10px;"
                  :precision="0"
                />
                <span style="margin-right: 5px;">单价:</span>
                <el-input-number
                  v-model="itemForm.price"
                  :min="0"
                  :step="0.01"
                  style="margin-right: 10px;"
                  :precision="2"
                />
                <el-button 
                  type="primary" 
                  @click="addItem"
                  :disabled="!canAddItem || loadingData || loading"
                  :loading="addingItem"
                >
                  添加
                </el-button>
            </div>

            <!-- 商品列表 -->
            <el-table
              v-if="formData.items.length > 0"
              :data="formData.items"
              style="margin-top: 20px;"
              stripe
            >
              <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
              <el-table-column prop="quantity" label="数量" width="150">
                <template #default="scope">
                    <el-input-number
                      v-model="scope.row.quantity"
                      :min="1"
                      @change="updateItemQuantity(scope.$index, $event)"
                      size="small"
                      :precision="0"
                      :disabled="loadingData || loading"
                    />
                  </template>
              </el-table-column>
              <el-table-column prop="price" label="单价" width="150">
                <template #default="scope">
                    <el-input-number
                      v-model="scope.row.price"
                      :min="0"
                      :step="0.01"
                      @change="updateItemPrice(scope.$index, $event)"
                      size="small"
                      :precision="2"
                      :disabled="loadingData || loading"
                    />
                  </template>
              </el-table-column>
              <el-table-column prop="subtotal" label="小计" width="120">
                <template #default="scope">
                  ¥{{ scope.row.subtotal.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="操作"  fixed="right">
                <template #default="scope">
                    <el-button
                      type="danger"
                      text
                      @click="handleRemoveItem(scope.$index, scope.row.name)"
                      :disabled="loadingData || loading"
                    >
                      删除
                    </el-button>
                  </template>
              </el-table-column>
            </el-table>

            <!-- 空状态 -->
              <div v-else class="empty-items">
                <el-empty description="暂无商品，请添加商品" :image-size="100" />
              </div>
          </div>
        </el-form-item>

        <!-- 订单总价 -->
          <el-form-item>
            <div class="total-price">
              <span>订单总价：</span>
              <span class="price">¥{{ calculateTotal().toFixed(2) }}</span>
              <span class="item-count">（共 {{ formData.items.length }} 件商品）</span>
            </div>
          </el-form-item>
      </el-form>
    </template>

    <template #footer>
        <el-button 
          @click="handleClose" 
          :disabled="loadingData || loading"
        >取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="loading"
          :disabled="!canSubmit || loadingData"
        >
          确定
        </el-button>
      </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, computed, onMounted } from 'vue';
import { Loading } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useEditOrderForm } from '../hooks/useEditOrderForm';

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  orderId: {
    type: [Number, String],
    default: null
  }
});

// Emits
const emit = defineEmits(['update:modelValue', 'success']);

// 表单引用
const orderFormRef = ref(null);

// 使用订单编辑表单hook
const {
  formData,
  loading,
  loadingData,
  itemForm,
  loadOrderData,
  addItem,
  removeItem,
  updateItemQuantity,
  updateItemPrice,
  calculateTotal,
  submitForm,
  resetForm
} = useEditOrderForm();

// 表单规则
const formRules = ref({
  customer_name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '客户姓名长度在1-50个字符之间', trigger: 'blur' }
  ],
  customer_phone: [
    { required: true, message: '请输入客户电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  order_time: [
    { required: true, message: '请选择下单时间', trigger: 'change' }
  ]
});

// 添加商品状态
const addingItem = ref(false);

// 记录初始数据用于判断是否有更改
const initialData = ref(null);

// 对话框可见性
const dialogVisible = ref(props.modelValue);

// 计算属性：是否可以添加商品
const canAddItem = computed(() => {
  return itemForm.name?.trim() && itemForm.quantity > 0 && itemForm.price >= 0;
});

// 计算属性：是否可以提交表单
const canSubmit = computed(() => {
  return formData.customer_name?.trim() && 
         formData.customer_phone?.trim() && 
         formData.order_time && 
         formData.items.length > 0;
});

// 监听对话框显示状态变化
watch(() => props.modelValue, async (newVal) => {
  dialogVisible.value = newVal;
  
  // 当对话框显示且有订单ID时，加载订单数据
  if (newVal && props.orderId) {
    await loadOrderData(props.orderId);
    // 加载数据后保存初始状态用于比较
    saveInitialData();
  }
});

// 监听订单ID变化（当对话框打开时切换订单）
watch(() => props.orderId, async (newVal) => {
  if (dialogVisible.value && newVal) {
    await loadOrderData(newVal);
    // 加载数据后保存初始状态用于比较
    saveInitialData();
  }
});

// 保存初始数据
const saveInitialData = () => {
  initialData.value = {
    customer_name: formData.customer_name,
    customer_phone: formData.customer_phone,
    order_time: formData.order_time ? new Date(formData.order_time) : null,
    items: JSON.parse(JSON.stringify(formData.items))
  };
};

// 处理电话号码输入
const handlePhoneInput = (value) => {
  // 只允许输入数字
  formData.customer_phone = value.replace(/[^0-9]/g, '');
};

// 处理移除商品
const handleRemoveItem = async (index, itemName) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品 "${itemName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    removeItem(index);
    ElMessage.success('商品已删除');
  } catch (error) {
    // 用户取消删除
  }
};

// 处理对话框关闭
const handleClose = () => {
  // 直接关闭对话框，不检查未保存的更改
  doClose();
};

// 执行关闭操作
const doClose = () => {
  resetForm();
  initialData.value = null;
  emit('update:modelValue', false);
};

// 检查是否有未保存的更改
const hasUnsavedChanges = () => {
  if (!initialData.value) return false;
  
  // 检查基本字段
  if (initialData.value.customer_name !== formData.customer_name ||
      initialData.value.customer_phone !== formData.customer_phone) {
    return true;
  }
  
  // 检查时间字段
  const initialTime = initialData.value.order_time ? new Date(initialData.value.order_time).getTime() : null;
  const currentTime = formData.order_time ? new Date(formData.order_time).getTime() : null;
  if (initialTime !== currentTime) {
    return true;
  }
  
  // 检查商品数量
  if (initialData.value.items.length !== formData.items.length) {
    return true;
  }
  
  // 检查商品详情
  for (let i = 0; i < formData.items.length; i++) {
    const oldItem = initialData.value.items[i];
    const newItem = formData.items[i];
    if (oldItem.name !== newItem.name ||
        oldItem.quantity !== newItem.quantity ||
        oldItem.price !== newItem.price) {
      return true;
    }
  }
  
  return false;
};

// 处理表单提交
const handleSubmit = async () => {
  // 验证表单
  if (!orderFormRef.value) return;
  
  try {
    await orderFormRef.value.validate();
    
    // 验证商品列表
    if (formData.items.length === 0) {
      ElMessage.error('订单至少需要包含一个商品');
      return;
    }
    
    const success = await submitForm();
    if (success) {
      emit('success');
      emit('update:modelValue', false);
    }
  } catch (error) {
    // 表单验证失败
    ElMessage.error('请完善订单信息');
  }
};
</script>

<style scoped>
.items-container {
  max-height: 400px;
  overflow-y: auto;
}

.add-item-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.empty-items {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.total-price {
  text-align: right;
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.total-price .price {
  color: #f56c6c;
  font-size: 22px;
  margin: 0 8px;
}

.total-price .item-count {
  color: #909399;
  font-size: 14px;
  font-weight: normal;
  margin-left: 5px;
}

.price {
  color: #f56c6c;
}

.loading-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #606266;
}

.is-loading {
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.el-table {
  --el-table-header-bg-color: #fafafa;
  margin-bottom: 10px;
  border-radius: 4px;
}

/* 优化表单验证提示 */
:deep(.el-form-item__error) {
  font-size: 12px;
}

/* 优化空状态间距 */
:deep(.el-empty) {
  margin: 20px 0;
}

/* 优化输入框宽度 */
.el-input-number {
  width: 120px;
}
</style>